JDK源码分析——AbstractOwnableSynchronizer类

抽象类AbstractOwnableSynchronizer该类是主要定义让线程以独占方式拥有同步器,此类为创建锁和相关同步器提供了基础,类本身不管理或使用此信息很简单的两个方法setExclusiveOwnerThread(Thread t)设置当前拥有独占访问的线程和getExclusiveOwnerThread()返回由setExclusiveOwnerThread最后设置的线程;如果从未设置,则返回null。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* A synchronizer that may be exclusively owned by a thread. This
* class provides a basis for creating locks and related synchronizers
* that may entail a notion of ownership. The
* {@code AbstractOwnableSynchronizer} class itself does not manage or
* use this information. However, subclasses and tools may use
* appropriately maintained values to help control and monitor access
* and provide diagnostics.
*
* @since 1.6
* @author Doug Lea
*/
// 一个线程,可能独占一个同步锁。AbstractOwnableSynchronizer用于表示锁与持有者之间的关系;
// AbstractOwnableSynchronizer不管理这种关系;主要是其子类,用于控制或监视锁的状态,提供帮助。
public abstract class AbstractOwnableSynchronizer
implements java.io.Serializable {

/** Use serial ID even though all fields transient. */
private static final long serialVersionUID = 3737899427754241961L;

/**
* Empty constructor for use by subclasses.
*/
protected AbstractOwnableSynchronizer() { }

/**
* The current owner of exclusive mode synchronization.
*/
// 独占模式,锁的持有者
private transient Thread exclusiveOwnerThread;

/**
* Sets the thread that currently owns exclusive access.
* A {@code null} argument indicates that no thread owns access.
* This method does not otherwise impose any synchronization or
* {@code volatile} field accesses.
* @param thread the owner thread
*/
// 设置锁持有者
protected final void setExclusiveOwnerThread(Thread thread) {
exclusiveOwnerThread = thread;
}

/**
* Returns the thread last set by {@code setExclusiveOwnerThread},
* or {@code null} if never set. This method does not otherwise
* impose any synchronization or {@code volatile} field accesses.
* @return the owner thread
*/
// 获取锁的持有线程
protected final Thread getExclusiveOwnerThread() {
return exclusiveOwnerThread;
}
}